<template>
  <div class="comment-statistics">
    <el-card class="filter-card">
      <div class="filter-container">
        <el-input
          v-model="productId"
          placeholder="输入商品ID查看具体商品的评论数据"
          clearable
          style="width: 250px"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="dateShortcuts"
          value-format="YYYY-MM-DD"
          @change="handleSearch"
        />
      </div>
    </el-card>

    <!-- 评论概览数据 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总评论数</span>
              <el-tooltip content="所有评论总数">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-value">{{ commentStats.totalComments || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>好评率</span>
              <el-tooltip content="好评数占总评论数的比例">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-value">{{ commentStats.positiveRate || '0%' }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均评分</span>
              <el-tooltip content="所有评论的平均评分">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-value">
            <el-rate
              v-model="commentStats.averageRating"
              disabled
              show-score
              text-color="#ff9900"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>评论回复率</span>
              <el-tooltip content="商家回复评论的比例">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-value">{{ commentStats.replyRate || '0%' }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 评分分布 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>评分分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="ratingOption" autoresize />
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>评论趋势</span>
              <el-select v-model="trendType" @change="handleTrendTypeChange">
                <el-option label="评论数量" value="count" />
                <el-option label="平均评分" value="rating" />
              </el-select>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="trendOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 评论关键词云 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>评论关键词云</span>
          <el-radio-group v-model="wordCloudType" @change="handleWordCloudTypeChange">
            <el-radio-button label="positive">正面评价</el-radio-button>
            <el-radio-button label="negative">负面评价</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div class="chart-container">
        <v-chart :option="wordCloudOption" autoresize />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, QuestionFilled } from '@element-plus/icons-vue'
import { getCommentStatistics } from '@/api/statistics'

// 数据定义
const productId = ref('')
const dateRange = ref([])
const commentStats = ref({})
const trendType = ref('count')
const wordCloudType = ref('positive')
const loading = ref(false)

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 获取评论统计数据
const fetchCommentStats = async () => {
  try {
    loading.value = true
    const response = await getCommentStatistics(productId.value || null)
    if (response.code === 200) {
      commentStats.value = response.data
    }
  } catch (error) {
    console.error('获取评论统计数据失败:', error)
    ElMessage.error('获取评论统计数据失败')
  } finally {
    loading.value = false
  }
}

// 评分分布图表配置
const ratingOption = computed(() => ({
  title: {
    text: '评分分布'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  xAxis: {
    type: 'category',
    data: ['1星', '2星', '3星', '4星', '5星']
  },
  yAxis: {
    type: 'value',
    name: '评论数'
  },
  series: [
    {
      name: '评论数量',
      type: 'bar',
      data: commentStats.value.ratingDistribution || [],
      itemStyle: {
        color: function(params) {
          const colors = ['#F56C6C', '#E6A23C', '#909399', '#67C23A', '#409EFF']
          return colors[params.dataIndex]
        }
      }
    }
  ]
}))

// 评论趋势图表配置
const trendOption = computed(() => ({
  title: {
    text: trendType.value === 'count' ? '评论数量趋势' : '评分趋势'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: commentStats.value.trendDates || []
  },
  yAxis: {
    type: 'value',
    name: trendType.value === 'count' ? '评论数' : '平均评分'
  },
  series: [
    {
      name: trendType.value === 'count' ? '评论数量' : '平均评分',
      type: 'line',
      smooth: true,
      data: trendType.value === 'count' 
        ? commentStats.value.commentCounts 
        : commentStats.value.ratingTrend,
      areaStyle: {
        opacity: 0.3
      }
    }
  ]
}))

// 词云图表配置
const wordCloudOption = computed(() => ({
  title: {
    text: wordCloudType.value === 'positive' ? '正面评价关键词' : '负面评价关键词'
  },
  tooltip: {
    show: true
  },
  series: [{
    type: 'wordCloud',
    shape: 'circle',
    left: 'center',
    top: 'center',
    width: '80%',
    height: '80%',
    right: null,
    bottom: null,
    sizeRange: [12, 60],
    rotationRange: [-90, 90],
    rotationStep: 45,
    gridSize: 8,
    drawOutOfBound: false,
    textStyle: {
      fontFamily: 'sans-serif',
      fontWeight: 'bold',
      color: function () {
        return 'rgb(' + [
          Math.round(Math.random() * 160),
          Math.round(Math.random() * 160),
          Math.round(Math.random() * 160)
        ].join(',') + ')'
      }
    },
    emphasis: {
      focus: 'self',
      textStyle: {
        shadowBlur: 10,
        shadowColor: '#333'
      }
    },
    data: wordCloudType.value === 'positive' 
      ? commentStats.value.positiveKeywords 
      : commentStats.value.negativeKeywords
  }]
}))

// 处理搜索
const handleSearch = () => {
  fetchCommentStats()
}

// 处理趋势类型变化
const handleTrendTypeChange = () => {
  // 图表会自动更新，因为使用了计算属性
}

// 处理词云类型变化
const handleWordCloudTypeChange = () => {
  // 图表会自动更新，因为使用了计算属性
}

// 初始化
onMounted(() => {
  fetchCommentStats()
})
</script>

<style scoped>
.comment-statistics {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.data-overview {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 400px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
}
</style> 